package com.enba.boot.es;

import java.io.IOException;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class EsHelper {

  private final RestHighLevelClient client;

  @Autowired
  public EsHelper(RestHighLevelClient client) {
    this.client = client;
  }

  public IndexResponse insert(String index, String id, String json) throws IOException {
    IndexRequest request = new IndexRequest(index).id(id).source(json, XContentType.JSON);
    return client.index(request, RequestOptions.DEFAULT);
  }

  public GetResponse get(String index, String id) throws IOException {
    GetRequest request = new GetRequest(index, id);
    return client.get(request, RequestOptions.DEFAULT);
  }

  public UpdateResponse update(String index, String id, String json) throws IOException {
    UpdateRequest request = new UpdateRequest(index, id).doc(json, XContentType.JSON);
    return client.update(request, RequestOptions.DEFAULT);
  }

  public DeleteResponse delete(String index, String id) throws IOException {
    DeleteRequest request = new DeleteRequest(index, id);
    return client.delete(request, RequestOptions.DEFAULT);
  }
}
